<?php
/**
 * Загрузка файлов из EvoGallery разных размеров
 * может служить как база для разных подобных модификаций
 *
 * @author tonatos
 */

class c_download_controller extends c_base_controller {

    public function index() {
        $id = (int) $_GET['id'];

        $m_type = $_GET['type'];

        if (empty($id))
            return "Ошибка в параметрах";

        global $modx;


        $photo = $modx->db->get_record("portfolio_galleries", "id=$id");

        $big_file = "assets/galleries/$photo->content_id/thumbs/big_$photo->filename";

        $path = MODX_BASE_PATH . "assets/galleries/$photo->content_id/thumbs/";


        switch ($m_type) {

            case "big";
                $this->push_file(MODX_BASE_PATH . $big_file, "big_$photo->filename");
                break;
            case "medium":
                $medium_file = $this->resize_and_save(MODX_BASE_PATH . $big_file, 1280, "medium", $path, $photo);
                $this->push_file($medium_file, "medium_$photo->filename");
                break;
            default:
                $small_file = $this->resize_and_save(MODX_BASE_PATH . $big_file, 1024, "small", $path, $photo);
                $this->push_file($small_file, "small_$photo->filename");
                break;
        }
    }

    protected function resize_and_save($big_file, $width, $type, $path, $photo) {


        $filename = "$path/{$type}_{$photo->filename}";

        if (file_exists(MODX_BASE_PATH . $filename)) {
            return $filename;
        }

        try {
            $thumb = PhpThumbFactory::create($big_file);
        } catch (Exception $e) {
            return $e->getMessage();
        }

        $thumb->resize($width);

        $thumb->save($filename, "JPG");

        return $filename;
    }

    /**
     * Отдача файла на загрузку
     * только для небольших файлов
     *
     * @param <type> $path
     * @param <type> $filename
     */

    protected function push_file($path, $filename) {
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . (string) (filesize($path)));
        header("Content-Disposition: inline; filename=$filename");
        header("Content-Transfer-Encoding: binary\n");

        readfile($path);
        die();
    }

}

?>